<?php
namespace Hawk\Model;
use Think\Model;
use Think\Model\RelationModel; 
class AdminModel extends RelationModel 
{
	protected $insertFields = array('username','pid','nickname','password','part','part_id','captcha','is_use','repassword');
	protected $updateFields = array('id','username','pid','nickname','part','part_id','password','captcha','is_use','repassword');
	protected $_validate = array(
		array('username', 'require', '用户名不能为空！', 1, 'regex', 3),
		array('username', 'require', '用户名必须唯一！', 1, 'unique', 3),
		array('nickname', 'require', '昵称不能为空！', 1, 'regex', 2),
		// array('part_id', 'require', '部门不能为空！', 1, 'regex', 1),
		array('password', 'require', '密码不能为空！', 1, 'regex', 1),
		array('repassword', 'password', '两次密码不一致', 1, 'confirm', 3),
	);
        public $_login_validate = array(
                array('username', 'require', '用户名不2222能为空！', 1, 'regex', 3),
		        array('password', 'require', '密码不2222能为空！', 1, 'regex', 3),
                array('captcha', 'require', '验证码不能为空！', 1, 'regex', 3),
                array('captcha', 'check_verify', '验证码错误！', 1, 'callback', 3),
        );
        // 检测输入的验证码是否正确，$code为用户输入的验证码字符串 
        public function check_verify($code, $id = ''){ 
        	$verify = new \Think\Verify(); 
        	return $verify->check($code, $id); 
        }
        /**
         * 登录
         * @author hawk <2271030162@qq.com>
         * @return mix
         */
        public function login(){
            $username = I('post.username');
            $password = I('post.password');

            $res = $this->where(
                    array(
                        'username'=>array('eq',$username),
                        ))->find();
            //用户是否存在
            if($res){
            //用户是否禁用
                if($res['id']==1 || $res['is_use']==1){
                    //查看密码是否正确
                    if(hawk_get_password($password)==$res['password']){                      
                            //存session值
                            session('staff_info',$res);
                            session('id',$res['id']);
                            session('username',$res['username']);
                            return true;
                    }  else {
                    $this->error = '密码错误！';
                    return false; 
                    }
                    
                }else{
                $this->error = '该用户已被禁用！';
                return false; 
                }
            }else {
                $this->error = '该用户不存在！';
                return false;
            }
        }
    /**
     * 多级
     * @author hawk <2271030162@qq.com>
     * @param  $where int
     * @return array
     */
    public function getPart($where)
    {
    	$pmodel=M('Part');
        $depart =$pmodel->where($where)->select();
        $menu = array();
        if($depart){
            foreach ($depart as $v) {
                //获取顶级数据
                if ($v['pid']==0) {
                    foreach ($depart as $v1) {
                        //获取二级数据
                        if ($v1['pid']==$v['id']) {
                            foreach ($depart as $v2) {
                                //获取三级数据
                                if ($v2['pid']==$v1['id']) {
                                    foreach($depart as $v3){
                                        //获取4级数据
                                        if($v3['pid']==$v2['id']){
                                            $v2['child'][]=$v3;
                                        }
                                    }
                                    $v1['child'][]=$v2;
                                }
                            }
                            $v['child'][]=$v1;
                        }
                    }
                    $menu[]=$v;
                }
            }
        }
        return $menu;
    }
    /**
     * 管理员ID转name
     * @author hawk <2271030162@qq.com>
     * @param  $id int
     * @return string
     */
    public function getAdminName($id){
        if(!empty($id)){
            $info = $this->find($id);
            return $info['nickname']; 
        }else{
            return "";
        }
        
    }
    /**
     *通过角色查管理员
     *@param $roleName string
     *@return $admin  array
     */
    public function getRoleToAdmin($roleName){
        $rmodel = M('Role');
        $role_self = $rmodel->where('role_name="'.$roleName.'"')->find();
        if(!empty($role_self)){
            $armodel = M('AdminRole');
            $admin_role = $armodel->where(array('role_id'=>array('eq',$role_self['id'])))->select();
            foreach ($admin_role as $k => $v) {
                $admin[] = $this->find($v['admin_id']);
            }           
            return $admin;  
        }
        
    }
	public function search($pageSize,$where=true)
	{
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
        $page->setConfig('first', '首页');
        $page->setConfig('last', '尾页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->field('a.*,p.name part_name,ar.role_id, r.role_name')->alias('a')->where($where)->group('a.id')->join('left join hawk_part p on a.part_id=p.id left join hawk_admin_role ar on a.id=ar.admin_id left join hawk_role r on ar.role_id=r.id')->limit($page->firstRow.','.$page->listRows)->select();
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
		$password = I('post.password');
		$data['password']=hawk_get_password($password);
		//hecho($data);exit;
	}
	//添加后
	protected function _after_insert($data, $option){
		$r_id = I('post.role_id');
		if ($r_id) {
			$armodel = M('AdminRole');
			foreach ($r_id as $k => $v) {
				$armodel->add(array(
					'role_id'=>$v,
					'admin_id'=>$data['id'],
				));
			}
		}
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
		//判断是否修改密码
		$pass = I('post.password');
		if (empty($pass)) {
			unset($data['password']);
		}else{

			$data['password']=hawk_get_password($pass);
            $data['first']=1;
		}
		$role_id = I('post.role_id');
		$armodel = M('AdminRole');
		if ($role_id) {
			$armodel->where("admin_id='".$option['where']['id']."'")->delete();//先删除
			foreach ($role_id as $k => $v) {
				$armodel->add(array(
					'role_id'=>$v,
					'admin_id'=>$option['where']['id'],
				));
			}			
		}
		$data['username']=I('post.username');
        if(!empty(I('post.part_id'))){
            $data['part_id']=I('post.part_id');
        }		
		//超管不可禁用
		if($option['where']['id']==1){
           $data['is_use'] = 1;
    	}else{
    		$data['is_use'] =I('post.is_use');
    	}
        $data=array_filter($data);
	}
    // 修改后
    protected function _after_update(&$data, $option)
    {
        if(!empty($data['password'])){
            session('staff_info')['password']=$data['password'];
        }
        if(!empty($data['username'])){
            session('staff_info')['username']=$data['username'];
        }
        if(!empty($data['nickname'])){
            session('staff_info')['nickname']=$data['nickname'];
        }

    }
	// 删除前
	protected function _before_delete($option)
	{
		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
		//判断是不是删除别人
        if(session('id')>1&&session('id')!=$option['where']['id']){
            $this->error = '你没有删除该户用的权限！';
            return FALSE;
        }
        $armodel = M('AdminRole');
		$armodel->where("admin_id='".$option['where']['id']."'")->delete();       
	}
    /************************************* 递归相关方法 *************************************/
    public function getTree(&$model,$part_id)
    {
        $data = $model->select();
        return $this->_reSort($model,$data,$part_id);
    }
    private function _reSort(&$model,$data, $part_id, $level=0, $isClear=TRUE)
    {
        static $ret = array();
        if($isClear)
            $ret = array();
        foreach ($data as $k => $v)
        {
            if($v['pid'] == $parent_id)
            {
                $v['level'] = $level;
                $ret[] = $v;
                $this->_reSort($model,$data, $v['id'], $level+1, FALSE);
            }
        }
        return $ret;
    }
    /**
     * 遍历子级元素
     * @author hawk <2271030162@qq.com>
     * @param  $id int
     * @return string
     */
    
    public function getChildren(&$model,$id)
    {
        $data = $model->select();
        return $this->_children($data, $id);
    }
    private function _children($data, $parent_id=0, $isClear=TRUE)
    {
        static $ret = array();
        if($isClear){
            $ret = array();
        }
        foreach ($data as $k => $v)
        {
            if($v['pid'] == $parent_id)
            {
                $ret[] = $v['id'];
                $this->_children($data, $v['id'], FALSE);
            }
        }
        return $ret;
    }
}